<template>
  <div class="plan-edit-box">
        <div class="plan-page-header" >
            <div class="header-title">{{this.title}}</div>
            <div class="header-btns" v-if="!disabledPage">
                <RPButton optType="reset" style="margin-right: 10px" @click="hideFun" text="取消" />
                <RPButton optType="create" style="margin-right: 10px" type="info" @click="save('save')" text="保存" />
                <RPButton optType="create" type="info" @click="save('saveAndSubmit')" text="保存并提交" />
            </div>
        </div>
        <div class="plan-page-content">
            <Form :model="addressGroupForm" :disabled="disabledPage" class="ivu-form-no-margin-bottom" ref="AddressGroupForm" :rules="rule" :label-width="200">
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                      <Form-item class="ivu-form-item ivu-form-item-required" prop="groupName" label="收件人组名：">
                          <Input v-model="addressGroupForm.groupName" :maxlength="50" :rows="4" placeholder="请输入" />
                      </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                      <Form-item prop="reportTypeCode" label="类型：">
                          <Select clearable v-model="addressGroupForm.reportTypeCode">
                            <Option
                            v-for="item in reportTypeList"
                            :value="item.vsiKey"
                            :key="item.vsiKey"
                            >{{ item.vsiValue }}</Option
                            >
                        </Select>
                      </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                      <Form-item prop="reportCode" label="领域：">
                          <Select clearable v-model="addressGroupForm.reportCode">
                            <Option
                            v-for="item in reportNameList"
                            :value="item.vsiKey"
                            :key="item.vsiKey"
                            >{{ item.vsiValue }}</Option
                            >
                        </Select>
                      </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                <Col span="24" style="border: none">
                    <Form-item prop="trgNodeNodeId" label="单位名称：">
                    <Select clearable ref="trgNodeNodeId" v-model="addressGroupForm.trgNodeNodeId">
                        <Option
                        v-for="item in bussinessUnitList"
                        :value="item.nodeId"
                        :key="item.nodeId"
                        >{{ item.text }}</Option
                        >
                    </Select>
                    </Form-item>
                </Col>
                </Row>
                <!-- <Row :gutter="20" class="code-row-bg">
                <Col span="24" style="border: none">
                    <Form-item prop="companyNodeId" label="所属二级组织：">
                    <Select v-model="addressGroupForm.companyNodeId" clearable>
                        <Option
                        v-for="item in secondOrganList"
                        :value="item.nodeId"
                        :key="item.nodeId"
                        >{{ item.text }}</Option
                        >
                    </Select>
                    </Form-item>
                </Col>
                </Row> -->
                <div class="addresee">
                    <Row :gutter="20" class="code-row-bg">
                    <Col span="24" style="border: none">
                        <Form-item prop="receiver" label="收件人：">
                          <div class="user-list">
                            <span style="color: #c5c8ce;"  v-show="receiverList.length == 0">请选择</span>
                            <div class="user" v-for="(item, index) in receiverList" :key="index">
                              <span class="user-name">{{item}}</span>
                              <Icon v-show="!disabledPage" type="ios-close" @click="removeUser(item, 'receiver')"/>
                            </div>
                          </div>
                          <Input v-show="false" v-model="addressGroupForm.receiver" type="textarea" :rows="4" placeholder="请输入" />
                        </Form-item>
                    </Col>
                    </Row>
                    <RPButton v-if="action != 'detail'" class="button" optType="create" text="选择" @click="SelectAdress"></RPButton>
                </div>
                <div class="addresee">
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                      <Form-item prop="ccs" label="抄送人：">
                      <!-- <Input v-model="addressGroupForm.ccs" type="textarea" :rows="4" placeholder="请输入" /> -->
                          <div class="user-list">
                            <span style="color: #c5c8ce;"  v-show="ccsList.length == 0">请选择</span>
                            <div class="user" v-for="(item, index) in ccsList" :key="index">
                              <span class="user-name">{{item}}</span>
                              <Icon v-show="!disabledPage" type="ios-close" @click="removeUser(item, 'css')"/>
                            </div>
                          </div>
                          <Input v-show="false" v-model="addressGroupForm.ccs" type="textarea" :rows="4" placeholder="请输入" />
                      </Form-item>
                  </Col>
                  </Row>
                  <RPButton v-if="action != 'detail'" class="button" optType="create" text="选择" @click="SelectCopy"></RPButton>
                </div>
            </Form> 
        </div>
  </div>
</template>

<script>
import SeleceAddressDatas from './SeleceAddressDatas'
import addressGroupApi from '@/api/addressGroup.js'
import ruleConfigApi from '@/api/ruleConfig.js'
import coverApi from '@/api/cover.js'
import editConfirm from './editConfirm'
import { 
  ADDRESS_GROUP_STATE_DRAFT,
  ADDRESS_GROUP_STATE_EFFECTIVE
} from './const.js'
export default {
    props:{
        title:{
            type: String,
            default() {
            return "";
            }
        },
        id: {
            type: String,
            default: ''
        },
        action: {
            type: String,
            default: 'create'
        },
        bussinessUnitList: {
            type: Array,
            default: () => []
        },
        disabledPage: {
            type: Boolean,
            default: false
        },
    },
    data(){
        const validatorGroupName =  (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入收件人组名'))
            } else {
                callback()
            }
            // else if (!/^([\u4e00-\u9fa5A-Za-z]){2,64}$/.test(value)) {
            //     callback(new Error('收件人组名仅支持中文、英文，2-64个字符'))
            // }
        }
        return{
           addressGroupForm:{
                id: '',
                groupName:'',
                trgNode: '',
                trgNodeNodeId: '',
                company: '',
                // companyNodeId: '',
                receiver:'',
                ccs:'',
                reportCode: '',
                reportName: '',
                reportTypeCode: '',
                reportType: ''
           },
          receiverList: [],
          ccsList: [],
          receiverListTrgList: [],
          ccsListTrgList: [],
          secondOrganList:[],
          rule:{
              groupName: [{ required: false, validator: validatorGroupName.bind(this), trigger: 'blur' }],
              trgNodeNodeId: [{ required: false, message: "请选择单位名称", trigger: "blur" }],
              receiver: [{ required: true, message: "请选择收件人", trigger: "blur" }],
              ccs: [{ required: true, message: "请选择抄送人", trigger: "blur" }],
              reportCode: [{ required: false, message: "请选择领域", trigger: "blur" }],
              reportTypeCode: [{ required: false, message: "请选择类型", trigger: "blur" }],
          },
          allreportNameList: [],
          reportNameList: [],
          reportTypeList: [],
          isEditOrDetailLoading: false
        }
    },
    methods:{
        hideFun() {
            this.$parent.hide()
        },
        getUserList() {
          return new Promise((resolve,reject)=>{
            coverApi.getRptTrgnodeTree({
              parentNodeCode: -1,
            }).then(res => {
              let data = res.data.data
              resolve(data)
            })
          })
          
        },
        removeUser(item, type) {
          if (type == 'receiver') {
            this.receiverList = this.receiverList.filter((user) => user !== item)
            this.receiverListTrgList = this.receiverListTrgList.filter(item => item.split('-')[0] == item)
            this.addressGroupForm.receiver = this.receiverList.length ? this.receiverList.join(',') : ''
          } else {
            this.ccsList = this.ccsList.filter((user) => user !== item)
            this.ccsListTrgList = this.ccsListTrgList.filter(item => item.split('-')[0] == item)
            this.addressGroupForm.ccs = this.ccsList.length ? this.ccsList.join(',') : ''
          }
        },
        async getAddressGroupDetail() {
            if (this.id) {
              let userlist = await this.getUserList()
              this.isEditOrDetailLoading = true
              addressGroupApi.getDetail({id: this.id}).then(res => {
                  if (res.data.code == 200) {
                      let result = res.data.data
                      let temp = {}

                      this.ccsList = result.ccs.length ? result.ccs.split(',') : []
                      if (result.ccs.length) {
                        result.ccs.split(',').forEach(item => {
                          let selectData = userlist.find(users => users.adminlist.includes(item))
                          if(selectData) {
                            this.ccsListTrgList.push(`${selectData.nodeId}-${item}`)
                          }
                        })
                      }
                      this.receiverList = result.receiver.length ? result.receiver.split(',') : []
                      if (result.receiver.length) {
                        result.receiver.split(',').forEach(item => {
                          let selectData = userlist.find(users => users.adminlist.includes(item))
                          if(selectData) {
                            this.receiverListTrgList.push(`${selectData.nodeId}-${item}`)
                          }
                        })
                      }

                      Object.keys(this.addressGroupForm).forEach(key => {
                          temp[key] = result[key]
                      })
                      this.addressGroupForm = temp
                      this.$nextTick(() => {
                        this.isEditOrDetailLoading = false
                      })
                  }
              })
            }
        },
        getSecondOrganList(nodeId) {
            coverApi.getRptTrgnodeTree({parentNodeCode: nodeId}).then(res => {
                let data = res.data.data
                let result = []
                if (data && data.length > 0) {
                    data.forEach(item => {
                    result.push({
                        text: item.nodeName,
                        value: item.nodeName,
                        nodeId: item.nodeId
                    })
                    })
                }
                // if (!result.find(item => item.nodeId == this.addressGroupForm.companyNodeId)) {
                //   this.addressGroupForm.companyNodeId = ''
                // }
                this.secondOrganList = result
            })
        },
        _editAddressGroup(params) {
            let msg = ''
            if (params.validFlag == ADDRESS_GROUP_STATE_DRAFT) {
                msg = '保存成功'
            } else if (params.validFlag == ADDRESS_GROUP_STATE_EFFECTIVE) {
                msg = '保存并提交成功'
            }
            addressGroupApi.editInfo(params).then(() => {
                this.$Message.success({
                    content: msg,
                    duration: 3
                });
                this.$emit('Close', true)
            }) 
        },
        editAddressGroupConfirm(data) {
            new this.$pageModal(
                editConfirm,
                {
                    props: {
                        data,
                        actionType: 'editAddressGroup'
                    }
                },
                (data) => {
                    this._editAddressGroup(data)
                }
            );
        },
        save(actionButton) {
           this.$refs["AddressGroupForm"].validate(valid => {
                if (valid) {
                    if (!this.addressGroupForm.reportCode) {
                      this.addressGroupForm.reportName = ''
                      this.addressGroupForm.reportCode = ''
                    } else {
                      let selectData = this.reportNameList.find(item => item.vsiKey == this.addressGroupForm.reportCode)
                      this.addressGroupForm.reportName = selectData.vsiValue
                    }
                    if (!this.addressGroupForm.reportTypeCode) {
                      this.addressGroupForm.reportType = ''
                      this.addressGroupForm.reportTypeCode = ''
                    } else {
                      let selectData = this.reportTypeList.find(item => item.vsiKey == this.addressGroupForm.reportTypeCode)
                      this.addressGroupForm.reportType = selectData.vsiValue
                    }
                    let params = JSON.parse(JSON.stringify(this.addressGroupForm))
                    if (actionButton == 'save') {
                        params.validFlag = ADDRESS_GROUP_STATE_DRAFT
                    } else if (actionButton == 'saveAndSubmit') {
                        params.validFlag = ADDRESS_GROUP_STATE_EFFECTIVE
                    }
                    if (this.id) {
                        ruleConfigApi.getReceiverGroupUsed({addressGroupId: this.id}).then(res => {
                            if (res.data.code == 200) {
                                let usedFlag = res.data.data
                                if (usedFlag == '1') {
                                    if (actionButton == 'save') {
                                        this.editAddressGroupConfirm(params)
                                    } else if (actionButton == 'saveAndSubmit') {
                                        this.$confirm({
                                            title: '',
                                            content: '该收件人组已作用于规则组，编辑后会将变化同步至规则组，您确定要编辑吗？'
                                        }).then(()=>{
                                            this._editAddressGroup(params)
                                        }).catch(() => {
                                            // this.createLoadding = false
                                        })
                                    }
                                } else {
                                    this._editAddressGroup(params)
                                }
                            }
                        })
                        // 编辑保存接口
                    } else {
                        // 新增保存接口
                        let msg = ''
                        if (params.validFlag == ADDRESS_GROUP_STATE_DRAFT) {
                            msg = '保存成功'
                        } else if (params.validFlag == ADDRESS_GROUP_STATE_EFFECTIVE) {
                            msg = '保存并提交成功'
                        }
                         addressGroupApi.createInfo(
                           params
                        ).then(() => {
                            this.$Message.success({
                                content: msg,
                                duration: 3
                            });
                            this.$emit('Close', true)
                            })
                    }

                } else {
                this.$Message.error({
                    content: '请完善表单信息',
                    duration: 3
                });
                    return 0;
                }
            });
        },
        SelectAdress(){
            new this.$pageModal(
               SeleceAddressDatas,
                {
                props: {
                    /* menuId: menu.id */
                    title:"选择收件人",
                }
                },
                (data) => {
                  if (data && data.length) {
                    data.forEach(item => {
                      if (!this.receiverList.find(user => user == item.name)) {
                        this.receiverList.push(item.name)
                        this.receiverListTrgList.push(item.org)
                      }
                    })
                  this.addressGroupForm.receiver = this.receiverList.join(',')
                   this.isSameGroup(this.addressGroupForm.trgNodeNodeId)
                  }
                }
            )
        },
        SelectCopy(){
            new this.$pageModal(
               SeleceAddressDatas,
                {
                props: {
                   /*  menuId: menu.id */
                   title:"选择抄送人"
                }
                },
                (data) => {
                  if (data && data.length) {
                    // this.addressGroupForm.ccs = data
                    data.forEach(item => {
                      if (!this.ccsList.find(user => user == item)) {
                        this.ccsList.push(item.name)
                        this.ccsListTrgList.push(item.org)
                      }
                    })
                    this.addressGroupForm.ccs = this.ccsList.join(',')
                    this.isSameGroup(this.addressGroupForm.trgNodeNodeId)
                  }
                }
            )
        },
        isSameGroup(currentNodeKey) {
          let allUserList = [...this.receiverListTrgList, ...this.ccsListTrgList]
          if (currentNodeKey && allUserList.length && allUserList.find(item => item.split('-')[0] !== currentNodeKey)) {
            this.addressGroupForm.trgNode = ''
            this.addressGroupForm.trgNodeNodeId = ''
            this.addressGroupForm.company = ''
            // this.addressGroupForm.companyNodeId = ''
            this.secondOrganList = []
            this.$refs.trgNodeNodeId.clearSingleSelect()
            this.$Message.error({
              content: '您选择的收件人或抄送人来自多个单位，请不要选择收件人组单位名称属性',
              duration: 3
            });
          }
        }
        
    },
    mounted(){

    },
    async created(){
        
        await coverApi.getCodeManage(
          {
            commonPageDTO: { currentPage: 1, pageSize: 10 },
            condition: { tenantCode: 'IT_SHARE_DEVELOP', vsCode: 'REPORT_FORM_TYPE' },
            pageNum: 1,
            pageSize: 10,
            sortDTO: { fieldName: '', orderBy: '' },
            tenantCode: 'IT_SHARE_DEVELOP',
            vsCode: 'REPORT_FORM_TYPE'
          }
        ).then(res => {
          this.reportTypeList = res.data.records
        })
        await coverApi.getCodeManage(
          {
            commonPageDTO: { currentPage: 1, pageSize: 10 },
            condition: { tenantCode: 'IT_SHARE_DEVELOP', vsCode: 'REPORT_FORMS' },
            pageNum: 1,
            pageSize: 10,
            sortDTO: { fieldName: '', orderBy: '' },
            tenantCode: 'IT_SHARE_DEVELOP',
            vsCode: 'REPORT_FORMS'
          }
        ).then(res => {
          this.allreportNameList = res.data.records
        })
        this.getAddressGroupDetail()
    },
    watch: {
        'addressGroupForm.trgNodeNodeId': {
            handler(val) {
                if (val) {
                    this.getSecondOrganList(val)
                    this.addressGroupForm.trgNode = this.bussinessUnitList.find(item => item.nodeId == val).text
                    if (!this.disabledPage) {
                      this.isSameGroup(val)
                    }
                } else {
                  this.addressGroupForm.trgNodeNodeId = ''
                }

            },
            immediate: true
        },
        // 'addressGroupForm.companyNodeId': {
        //     handler(val) {
        //         if (val) {
        //             this.addressGroupForm.company = this.secondOrganList.find(item => item.nodeId == val) ? this.secondOrganList.find(item => item.nodeId == val).value : ''
        //         } else {
        //             this.addressGroupForm.companyNodeId = ''
        //         }
        //     },
        //     immediate: true
        // },
        'addressGroupForm.reportTypeCode': {
             handler(val) {
                this.reportNameList = val ? this.allreportNameList.filter(item => item.vsiParentKey == val) : []
                if (!this.isEditOrDetailLoading) {
                  this.addressGroupForm.reportCode = ''
                  this.addressGroupForm.reportName = ''
                }
            },
            immediate: true
        }
        
    }
}
</script>

<style lang="less" scoped>

.plan-edit-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .plan-page-header {
    display: flex;
    justify-content: space-between;
    height: 60px;
    align-items: center;
    padding: 0 20px;
    .header-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .plan-page-content {
    flex: 1;
    overflow-y: scroll;
    overflow-x: hidden;
    padding: 0 20%;
  }

 /deep/.ivu-btn-warning {
    padding: 4px 23px;
    background-color: #ff6f4b;
    border-color: #ff6f4b;
    border-radius: 0;
} 
.addresee{
    position: relative;
    .button {
      position: absolute;
      right: -100px;
      top: 0;
    }
}
.button{
    //margin-left:530px !important;
    margin-left:15px !important;
} 
}
.user-list {
  width: 100%;
  min-height: 32px;
  border: 1px solid #d8d8d8;
  padding: 2px 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .user{
    height: 26px;
    line-height: 26px;
    background: #f5f5f5;
    padding: 0 10px;
    border-radius: 5px;
    margin: 3px 5px;
    .user-name {
      margin-right: 4px;
    }
    .ivu-icon-ios-close {
      font-size: 18px;
      cursor: pointer;
    }
  }
}
</style>
